<template>
  <a-modal
    v-model:open="open"
    :title="
      oType === 'view'
        ? '任务概览'
        : oType === 'edit'
        ? '编辑离线任务'
        : '创建离线任务'
    "
    :footer="null"
    width="40%"
    @cancel="closeDrawer"
    destroyOnClose
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      layout="horizontal"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      style="max-width: 700px; margin: 0 auto"
    >
      <a-form-item label="任务名称" name="flowName" required>
        <a-input
          v-model:value="form.flowName"
          :disabled="oType === 'view'"
          placeholder="请输入任务名称"
        />
      </a-form-item>
      <a-form-item label="任务描述" name="flowDesc">
        <a-input
          v-model:value="form.flowDesc"
          :disabled="oType === 'view'"
          placeholder="请输入任务描述"
        />
      </a-form-item>
      <!-- <a-form-item label="流程组" name="groupId" required>
        <a-select
          v-model:value="form.groupId"
          :disabled="oType === 'view'"
          placeholder="请选择流程组"
        >
          <a-select-option
            v-for="item in groupList"
            :key="item.id"
            :value="item.id"
            >{{ item.flow_group_name }}</a-select-option
          >
        </a-select>
      </a-form-item> -->
      <a-form-item
        label="选择源库类型"
        name="sourceType"
        required
        v-if="oType !== 'edit'"
      >
        <a-select
          v-model:value="form.sourceType"
          :disabled="oType === 'view'"
          placeholder="请选择源库类型"
          @change="changeSourceType"
        >
          <a-select-option
            v-for="item in sourceTypeList"
            :key="item.dbConfId"
            :value="item.dbConfName"
            >{{ item.dbConfName }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item
        label="选择目标库类型"
        name="targetTypes"
        required
        v-if="oType !== 'edit'"
      >
        <a-select
          v-model:value="form.targetTypes"
          mode="multiple"
          placeholder="点击进行选择（可多选）"
          :disabled="oType === 'view'"
        >
          <a-select-option
            v-for="item in targetTypeList"
            :key="item.dbConfId"
            :value="item.dbConfName"
            >{{ item.dbConfName }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item
        label="上传文件"
        name="file"
        required
        v-if="oType !== 'edit'"
      >
        <a-upload
          :before-upload="beforeUpload"
          :file-list="fileList"
          :max-count="1"
          :show-upload-list="true"
          :disabled="oType === 'view'"
        >
          <a-button>选择文件</a-button>
        </a-upload>
      </a-form-item>
    </a-form>
    <div class="modal-footer">
      <a-button @click="closeDrawer" style="margin-right: 10px">取消</a-button>
      <a-button type="primary" @click="handleSubmit" v-if="oType !== 'view'"
        >确认</a-button
      >
    </div>
  </a-modal>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import * as http from "@/api/flow/createTask.js";
import request from "@/utils/unite";
import emiter from "@/plugins/bus.js";
const open = ref(false);
const formRef = ref();
const form = reactive({
  flowName: "",
  flowDesc: "",
  groupId: "",
  sourceType: "",
  targetTypes: [],
  file: null,
  flowId: "",
});
const fileList = ref([]);
const groupList = ref([
  { value: "group1", label: "流程组1" },
  { value: "group2", label: "流程组2" },
]);
const sourceTypeList = ref([]);
const targetTypeList = ref([]);

const rules = {
  flowName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  groupId: [{ required: true, message: "请选择流程组", trigger: "change" }],
  sourceType: [
    { required: true, message: "请选择源库类型", trigger: "change" },
  ],
  targetTypes: [
    {
      required: true,
      type: "array",
      min: 1,
      message: "请选择目标库类型",
      trigger: "change",
    },
  ],
  file: [{ required: true, message: "请上传文件", trigger: "change" }],
};
// 是否是编辑
const isEdit = ref(0); // 0 不回显 1 回显
const oType = ref("add"); // add 新增 view 查看 edit 编辑

function beforeUpload(file) {
  form.file = file;
  fileList.value = [file];
  return false;
}

function changeSourceType(value) {
  // 可根据源库类型动态获取目标库类型
  // 这里直接复用 sourceTypeList 作为 targetTypeList 示例
  targetTypeList.value = sourceTypeList.value;
}

async function handleSubmit() {
  if (oType.value === "view") {
    return;
  } else if (oType.value === "edit") {
    const formData = new FormData();
    formData.append("flowId", form.flowId);
    formData.append("flowName", form.flowName);
    formData.append("flowDesc", form.flowDesc);
    formData.append("flowType", 1);
    formData.append("deployMode", 2); // 离线
    formData.append("reserve2",form.sourceType);
    formData.append("reserve4", form.targetTypes.join(","));
    formData.append("file", form.file);
    // formData.append("userGroupId", 1);
    // formData.append("groupId", form.groupId);
    formData.append("tokenID",  window.sessionStorage.getItem('Admin-Token'));
    //   try {
      let params = {
      type:'formData',
      formData
    }
    const res = await http.saveCMFlowInfo(params);
    if (res.code === "000000") {
      emiter.emit("refreshFun", null);
      closeDrawer();
    } else {
      message.error(res.msg || "编辑失败");
    }
  } else {
    const getrandom = () => {
      var str = "";
      for (var i = 0; i < 5; i++) {
        // str += (Math.random() * 10).toFixed(0);
        str += (Math.random() * 3).toFixed(0);
      }
      return str;
    };
    await formRef.value.validate();
    const formData = new FormData();
    formData.append("flowId", Date.now() + getrandom());
    formData.append("flowName", form.flowName);
    formData.append("flowDesc", form.flowDesc);
    formData.append("flowType", 1);
    formData.append("deployMode", 2); // 离线
    formData.append("reserve2",form.sourceType);
    formData.append("reserve4", form.targetTypes.join(","));
    formData.append("file", form.file);
    // formData.append("userGroupId", 1);
    // formData.append("groupId", form.groupId);
    formData.append("tokenID",  window.sessionStorage.getItem('Admin-Token'));
    //   try {
      let params = {
      type:'formData',
      formData
    }
    const res = await http.saveCMFlowInfo(params);
    if (res.code === "000000") {
      message.success("创建成功");
      emiter.emit("refreshFun", null);
      closeDrawer();
      
    } else {
      message.error(res.msg || "创建失败");
    }
    //   } catch (e) {
    //     message.error("接口异常");
    //   }
  }
}

async function openDrawer(record, type) {
  isEdit.value = record ? 1 : 0;
  oType.value = type;
  resetForm();
  open.value = true;
  await initGroups();
  await initSourceType();
  // 回显信息
  if (record) {
    queryCMFlowInfo(record);
  }
}
// 回显信息
async function queryCMFlowInfo(record) {
  console.log(record, "record");
  let params = {
    flowId: record.flowId,
  };
  let res = await http.queryCMFlowInfo(params);
  try {
    if (res.code == "000000" && res.data) {
      const d = res.data;
      Object.assign(form, {
        flowName: d.flowName,
        flowDesc: d.flowDesc,
        groupId: d.userGroupId,
        sourceType: d.dbType,
        targetTypes: d.reserve2.split(","),
        file: d.file ? JSON.parse(d.file) : null,
        flowId: d.flowId
      });
      fileList.value = form.file ? [form.file] : [];
    }
  } catch (error) {
    console.log(error);
    message.error(error);
  }
}

function closeDrawer() {
  open.value = false;
  isEdit.value = 0;
  oType.value = "add";
  resetForm();
}

async function initGroups() {
  const res = await http.getGroup({
    type: "all",
  });
  groupList.value = res.data;
}

const initSourceType = async () => {
  const params = { userID: window.sessionStorage.getItem("userId") };
  const res = await http.getDataBaseTypeInfo(params);
  sourceTypeList.value = res.data;
  targetTypeList.value = res.data;
};
function resetForm() {
  form.flowName = "";
  form.flowDesc = "";
  form.groupId = "";
  form.sourceType = "";
  form.targetTypes = [];
  form.file = null;
  fileList.value = [];
  if (formRef.value) formRef.value.resetFields();
}

// 获取源端类型（参考 TaskDeployment.vue）
onMounted(async () => {});

import { defineExpose } from "vue";
defineExpose({ openDrawer });
</script>
<style scoped>
.modal-footer {
  text-align: right;
  margin-top: 8px;
}
</style>
